#include "ExampleList.h"

#include <iostream>

CONFIG_EXAMPLE(ExampleList)
{
	this->cur_example = nullptr;
}

void ExampleList::addExample(Example* example)
{
	const std::string cur_example_name = example->getName();
	if (this->examples.find(cur_example_name) != this->examples.end())
	{
		delete this->examples[cur_example_name];
	}
	this->examples[cur_example_name] = example;
}

void ExampleList::execute()
{
	std::string cur_command;
	bool if_break = false;
	while(!if_break)
	{
		LOG_SHELL__(>>) << std::flush;
		std::cin >> cur_command;
		{
			if (cur_command == "exit")
			{
				LOG_SUCCESS(Bye!) << std::endl;
				if_break = true;
			}
			else if (cur_command == "list")
			{
				for (auto& example : this->examples)
				{
					LOG_V_WARNING(example.first) << std::endl;
				}
			}
			else if (this->examples.find(cur_command) != this->examples.end())
			{
				this->cur_example = this->examples[cur_command];
			}
			else
			{
				LOG_WARNING(This example is not registered!) << std::endl;
			}
		}
		if (this->cur_example)
		{
			std::string cur_example_name = this->cur_example->getName();
			LOG_V_DEBUG__("Set up example: ") << cur_example_name << std::endl;
			this->cur_example->setUp();
			LOG_V_DEBUG__("Execute example: ") << cur_example_name << std::endl;
			this->cur_example->execute();
			LOG_V_DEBUG__("Tear down example: ") << cur_example_name << std::endl;
			this->cur_example->tearDown();
			this->cur_example = nullptr;
		}
	}
}

void ExampleList::tearDown()
{
	for (auto& example : this->examples)
	{
		delete example.second;
	}
	this->examples.clear();
}
